package com.stylefeng.guns.rest.modular.wz.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.stylefeng.guns.rest.common.base.controller.ApiBaseController;
import com.stylefeng.guns.rest.common.constant.Consts;
import com.stylefeng.guns.rest.common.persistence.dao.*;
import com.stylefeng.guns.rest.common.persistence.model.*;
import com.stylefeng.guns.rest.domain.ParamMap;
import com.stylefeng.guns.rest.domain.Res;
import com.stylefeng.guns.rest.modular.wz.cache.CacheService;
import com.stylefeng.guns.rest.modular.wz.service.impl.WzAdvUserServiceImpl;
import com.stylefeng.guns.rest.modular.wz.service.impl.WzUserServiceImpl;
import com.stylefeng.guns.rest.modular.wz.util.AliPushUtil;
import com.stylefeng.guns.rest.modular.wz.util.weixin.AdvancedUtil;
import com.stylefeng.guns.rest.modular.wz.util.weixin.SNSUserInfo;
import com.stylefeng.guns.rest.modular.wz.util.weixin.WeixinOauth2Token;
import com.stylefeng.guns.rest.modular.wz.util.wz.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.math.BigDecimal;
import java.util.*;

@RestController
@RequestMapping("/wz/test/")
public class WzTestController extends ApiBaseController{

    @Autowired
    private WzUserMapper userMapper;
    @Autowired
    private WzUserAdvRecordMapper userAdvRecordMapper;
    @Autowired
    private WzUserAdvCollectionMapper userAdvCollectionMapper;
    @Autowired
    private WzUserCouponMapper userCouponMapper;
    @Autowired
    private WzUserFixedInfoMapper userFixedInfoMapper;
    @Autowired
    private WzUserQuestionnaireMapper userQuestionnaireMapper;
    @Autowired
    private WzPrizeWinnersMapper prizeWinnersMapper;
    @Autowired
    private WzUserFinanceRecordMapper userFinanceRecordMapper;
    @Autowired
    private WzUserOauthMapper userOauthMapper;
    @Autowired
    private WzAdvUserMapper advUserMapper;
    @Autowired
    private WzUserMessageMapper userMessageMapper;
    @Autowired
    private WzUserRecommendMapper userRecommendMapper;
    @Autowired
    private WzAnswerMapper answerMapper;
    @Autowired
    private WzAdvCommentMapper advCommentMapper;
    @Autowired
    private WzUserServiceImpl userService;
    @Autowired
    private WzAdvMapper advMapper;
    @Autowired
    private WzAdvUserServiceImpl advUserService;
    @Autowired
    private WzAdvMapMapper advMapMapper;
    @Autowired
    private CacheService cacheService;


    //年龄
    @PostMapping("test")
    public int test() throws Exception{
        List<WzAdvMap> advMaps = advMapMapper.selectList(new EntityWrapper<WzAdvMap>());
        for(WzAdvMap advMap:advMaps){
            WzUser user = cacheService.user(advMap.getUserCode());
            user.setHasAdvMap(1);
        }
        return 1;
    }


    //年龄
//    @RequestMapping("test")
//    public String test(){
//        List<WzUser> users = userMapper.selectList(new EntityWrapper<WzUser>().ne("birthday",""));
//        for(WzUser user:users){
//            String a = user.getBirthday();
//            a = a.substring(0,4);
//            user.setAge(Integer.parseInt(a));
//        }
//        userService.updateBatchById(users);
//        return "test";
//    }

    /**
     * 新闻评论
     */
//    @RequestMapping("test")
//    public void test(HttpServletResponse response, String advId, HttpServletRequest request) throws Exception{
//        List<WzAdvComment> advComments = advCommentMapper.selectList(new EntityWrapper<WzAdvComment>().isNotNull("reply_user_code"));
//        for(WzAdvComment advComment:advComments){
//            List<WzAdvComment> advCommentList = advCommentMapper.selectList(new EntityWrapper<WzAdvComment>().eq("user_code",advComment.getReplyUserCode()).eq("adv_id",advComment.getAdvId()));
//            if(advCommentList.size() > 0){
//                advComment.setMainUserCode(advCommentList.get(0).getAdvCommentId());
//                int r = advCommentMapper.updateById(advComment);
//                WzAdvComment advComment1 = advCommentMapper.selectById(advCommentList.get(0).getAdvCommentId());
//                advComment1.setMainUserCode(advCommentList.get(0).getAdvCommentId());
//                advComment1.setReplyNumber(1);
//                advComment1.setHasUserComment(1);
//                r = advCommentMapper.updateById(advComment1);
//                System.out.println("a");
//            }
//            System.out.println("a");
//        }
//    }


    /**
     * 性别
     */
//    @RequestMapping("test")
//    public ModelAndView test(){
//        List<WzUser> users = userMapper.selectList(new EntityWrapper<WzUser>().eq("gender",0));
//        int a = 0;
//        int b = 0;
//        for(WzUser user:users){
//            List<WzUserFixedInfo> userFixedInfos = userFixedInfoMapper.selectList(new EntityWrapper<WzUserFixedInfo>().eq("user_code",user.getUserCode()).in("gender",new Integer[]{1,2}));
//            if(userFixedInfos.size() > 0){
//                user.setGender(userFixedInfos.get(0).getGender());
//                userMapper.updateById(user);
//                a++;
//            }else{
//                List<WzUserOauth> userOauths = userOauthMapper.selectList(new EntityWrapper<WzUserOauth>().eq("user_code",user.getUserCode()).in("gender",new Integer[]{1,2}));
//                if(userOauths.size() > 0){
//                    user.setGender(userOauths.get(0).getGender());
//                    userMapper.updateById(user);
//                    b++;
//                }
//            }
//        }
//        System.out.println(a);
//        System.out.println(b);
//        return null;
//    }

//    @RequestMapping("test")
//    public ModelAndView test(){
//        System.out.println("test");
//        ModelAndView modelAndView = new ModelAndView("/static/data");
//        return modelAndView;
//    }

    /** MP_verify_o2FHVNJqv9FH0BYP.txt
     * 邀请码 975626684187279562 1007537147158085634
     */
//    @PostMapping("test")
//    public int test(){
//        List<WzUser> users = userMapper.selectList(new EntityWrapper<WzUser>().eq("mobile_type","100"));
//        for(WzUser user:users){
//            Long userCode = user.getUserCode();
//            //删除广告领钱记录
//            userAdvRecordMapper.delete(new EntityWrapper<WzUserAdvRecord>().eq("user_code",userCode));
//            //删除广告收藏记录
//            userAdvCollectionMapper.delete(new EntityWrapper<WzUserAdvCollection>().eq("user_code",userCode));
//            //删除中奖记录
//            prizeWinnersMapper.delete(new EntityWrapper<WzPrizeWinners>().eq("user_code",userCode));
//            //删除用户礼券记录
//            userCouponMapper.delete(new EntityWrapper<WzUserCoupon>().eq("user_code",userCode));
//            //删除账户资金记录
//            userFinanceRecordMapper.delete(new EntityWrapper<WzUserFinanceRecord>().eq("user_code",userCode));
//            //删除调查问卷记录
//            userQuestionnaireMapper.delete(new EntityWrapper<WzUserQuestionnaire>().eq("user_code",userCode));
//            //删除用户广告用户
//            advUserMapper.delete(new EntityWrapper<WzAdvUser>().eq("user_code",userCode));
//            //删除用户消息
//            userMessageMapper.delete(new EntityWrapper<WzUserMessage>().eq("user_code",userCode));
//            //删除用户邀请码记录
//            userRecommendMapper.delete(new EntityWrapper<WzUserRecommend>().eq("accept_user_code",userCode));
//            //删除用户固定信息
//            userFixedInfoMapper.delete(new EntityWrapper<WzUserFixedInfo>().eq("user_code",userCode));
//            //删除用户三方登录信息
//            userOauthMapper.delete(new EntityWrapper<WzUserOauth>().eq("user_code",userCode));
//            //删除用户账号
//            userMapper.delete(new EntityWrapper<WzUser>().eq("user_code",userCode));
//        }
//        return users.size();
//    }

//    @PostMapping("test")
//    public Map test(){
//        // remainSize 剩余的红包数量
//        // remainMoney 剩余的钱 ,2,BigDecimal.ROUND_HALF_UP
//        int remainSize = 1000;
//        BigDecimal remainMoney = new BigDecimal("130");
//        BigDecimal  a = new BigDecimal("0");
//        String res = "";
//        String res2 = "";
//        int s = 0;
//        int ss = 0;
//        double mk = 0;
//        int peilv = remainSize/200;
//        if(peilv >= 15){
//            peilv = 15;
//        }else if(peilv < 10){
//            peilv = 10;
//        }
//        int number = remainSize;
//        for(int i = 0;i < number;i++){
//            if (remainSize == 1) {
//                remainSize--;
//                a = a.add(remainMoney).setScale(2,   BigDecimal.ROUND_HALF_UP);
//                res = res + ","+(i+1);
//                res2 = res2 +","+remainMoney;
//                if(remainMoney.doubleValue() > mk){
//                    mk = remainMoney.doubleValue();
//                }
//                break;
//            }
//            double min  = 0.01;
//            BigDecimal b = remainMoney.divide(new BigDecimal(remainSize),2, BigDecimal.ROUND_HALF_EVEN);
//            BigDecimal max = new BigDecimal("0");
//            Random r  = new Random();
//                int num = r.nextInt(number);
//                double ratio = remainSize*0.18;
//                if(0<num && num <= ratio){
//                    s++;
//                    ratio = remainSize*0.01;
//                    if(0<num && num <= ratio){
//                        ss++;
//                        max = b.multiply(new BigDecimal(peilv));
//                        System.out.println(max);
//                    }else{
//                        if(b.compareTo(new BigDecimal(0.1)) == -1){
//                            max = b.multiply(new BigDecimal(peilv));
//                        }else{
//                            BigDecimal gg = b.subtract(new BigDecimal(0.09)).setScale(2, BigDecimal.ROUND_HALF_EVEN);
//                            BigDecimal g = new BigDecimal(peilv).subtract(gg.multiply(new BigDecimal(100))).setScale(0, BigDecimal.ROUND_HALF_EVEN);
//                            if(g.compareTo(new BigDecimal(6)) == -1){
//                                g = new BigDecimal(6);
//                            }
//                            max = b.multiply(g);
//                        }
//                    }
//                }else{
//                    if(i < remainSize/2){
//                        max = b.multiply(new BigDecimal("1.4"));
//                    }else{
//                        max = b.multiply(new BigDecimal("1.8"));
//                    }
//                }
//            BigDecimal m  = new BigDecimal(r.nextDouble()*max.doubleValue());
//            double money = m.setScale(2,   BigDecimal.ROUND_HALF_UP).doubleValue();
//            money = money <= min ? 0.01: money;
//            remainSize--;
//            remainMoney = remainMoney.subtract(new BigDecimal(money)).setScale(2,   BigDecimal.ROUND_HALF_UP);
//            System.out.println(money);
//            if(money > mk){
//                mk = money;
//            }
//            if(i == 0){
//                res = "1";
//                res2 = res2 +money;
//            }else{
//                res = res + ","+(i+1);
//                res2 = res2 +","+money;
//            }
//            a = a.add(new BigDecimal(money)).setScale(2,   BigDecimal.ROUND_HALF_UP);
//        }
//        System.out.println(a);
//        System.out.println(mk);
//        Map map= new HashMap();
//        map.put("res",res);
//        map.put("res2",res2);
//        map.put("a",a);
//        map.put("mk",mk);
//        map.put("s",s);
//        map.put("ss",ss);
//        return map;
//    }

    /**
     * 推送测试
     */
    @PostMapping("push.test")
    public Res pushTest(@RequestBody ParamMap paramMap) throws Exception{
        int subtype = paramMap.getIntMisValid("subtype");//1、推送消息;2、推送通知;3、高级推送
        String title = paramMap.getStrMisValid("title");
        String content = paramMap.getStrMisValid("content");
        String userCode = paramMap.getStrMisValid("userCode");
        JSONObject j = new JSONObject();
        j.put("coverUrl", "");
        j.put("hasDetail", 0);
        j.put("questionnaireId", "");
        j.put("advId", "1012993759440265218");
        j.put("advUserId", "");
        j.put("title", "");
        j.put("subtype", "1");
        if(subtype == 1){
            AliPushUtil.pushMessageToAndroid(title,content,null);
        }else if(subtype == 2){
            AliPushUtil.pushMessageToIOS(title,content,null);
        }else if(subtype == 3){
            int type = paramMap.getIntMisValid("type");
            AliPushUtil.pushNoticeToIOSAccount(userCode,title,content,type,j);
        }else if(subtype == 4){
            int type = paramMap.getIntMisValid("type");
            AliPushUtil.pushNoticeToAndroid(userCode,title,content,type,j);
        }else if(subtype == 5){//推送全部
            AliPushUtil.pushNoticeToAll(title,content);
        }
        return Res.success();
    }


    /**
     * 删除账号数据（广告领钱记录、广告收藏记录、中奖记录、用户礼券记录、账户资金记录、调查问卷记录）
     */
    @PostMapping("del.userData")
    public Res delUserData(@RequestBody ParamMap paramMap){
        String  account = paramMap.getStrMisValid("account");
        if(!account.equals("17521154550") && Consts.dev.equals("false")){
            return Res.success("帐号错误!");
        }
        int  type = paramMap.getIntValid("type");//1、删除用户所有数据;2、删除所有用户数据;3、删除用户账号;
        if(type == 1){
            List<WzUser> userList = userMapper.selectList(new EntityWrapper<WzUser>().eq("account",account));
            if(userList.size() > 0){
                Long userCode = userList.get(0).getUserCode();
                //删除广告领钱记录
                userAdvRecordMapper.delete(new EntityWrapper<WzUserAdvRecord>().eq("user_code",userCode));
                //删除广告收藏记录
                userAdvCollectionMapper.delete(new EntityWrapper<WzUserAdvCollection>().eq("user_code",userCode));
                //删除中奖记录
                prizeWinnersMapper.delete(new EntityWrapper<WzPrizeWinners>().eq("user_code",userCode));
                //删除用户礼券记录
                userCouponMapper.delete(new EntityWrapper<WzUserCoupon>().eq("user_code",userCode));
                //删除账户资金记录
                userFinanceRecordMapper.delete(new EntityWrapper<WzUserFinanceRecord>().eq("user_code",userCode));
                //删除调查问卷记录
                userQuestionnaireMapper.delete(new EntityWrapper<WzUserQuestionnaire>().eq("user_code",userCode));
                //删除用户广告用户
                advUserMapper.delete(new EntityWrapper<WzAdvUser>().eq("user_code",userCode));
                //删除用户消息
                userMessageMapper.delete(new EntityWrapper<WzUserMessage>().eq("user_code",userCode));
                //删除用户邀请码记录
                userRecommendMapper.delete(new EntityWrapper<WzUserRecommend>().eq("accept_user_code",userCode));
            }else{
                return Res.fail("账号不存在或输入错误!");
            }
        }else if(type == 2){//删除单个用户账号
            account = paramMap.getStrMisValid("account");
            List<WzUser> userList = userMapper.selectList(new EntityWrapper<WzUser>().eq("account",account));
            if(userList.size() > 0){
                Long userCode = userList.get(0).getUserCode();
                //删除用户固定信息
                userFixedInfoMapper.delete(new EntityWrapper<WzUserFixedInfo>().eq("user_code",userCode));
                //删除用户三方登录信息
                userOauthMapper.delete(new EntityWrapper<WzUserOauth>().eq("user_code",userCode));
                //删除用户账号
                userMapper.delete(new EntityWrapper<WzUser>().eq("user_code",userCode));
            }else{
                return Res.fail("账号不存在或输入错误!");
            }
        }
        return Res.success("数据删除成功!");
    }
}
